<template>
  <div class="category-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <div class="search-area">
        <el-input v-model="searchForm.name" placeholder="输入类别名称查询" style="width: 200px; margin-right: 10px;" />
        <el-select v-model="searchForm.status" placeholder="显示启用类别" style="width: 150px; margin-right: 10px;">
          <el-option label="全部" value="-1"></el-option>
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <el-button type="primary" @click="searchCustomerType">查询</el-button>
      </div>

      <div class="action-buttons">
        <el-button class="!ml-0" type="primary" @click="openAddDialog">
          新增
        </el-button>
        <el-button @click="batchClose">禁用</el-button>
        <el-button @click="batchOpen">启用</el-button>
        <el-button @click="refresh">刷新</el-button>
      </div>


      <el-dialog v-model="dialogFormVisible" :title="dialogCustomerType === 'add' ? '新增客户类别' : '修改客户类别'" width="500">
        <el-form :model="form">
          <el-form-item label="上级分类" :label-width="formLabelWidth">
            <el-tree-select v-model="form.parentId" :data="treeSelectData" filterable style="width: 240px"
              :props="{ value: 'id', label: 'name', children: 'children' }" :check-strictly="true">

              <template #default="{ data }">
                <span>
                  <el-icon>
                    <Folder v-if="data.children && data.children.length > 0" />
                    <Document v-else />
                  </el-icon>
                  {{ data.name }}
                </span>
              </template>
            </el-tree-select>
          </el-form-item>

          <el-form-item label="类别名称" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" style="width: 240px" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="saveCustomerType" :loading="saving">
              确认
            </el-button>
            <el-button @click="dialogFormVisible = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 数据表格 -->
    <el-table :data="searchMode ? customerTypeList : treeData" border style="width: 100%" row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :default-expand-all="!searchMode"
      v-loading="tableLoad" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="类别" width="300">
        <template #default="{ row }">
          {{ row.name }}
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" width="150">
        <template #default="{ row }">
          <el-switch :model-value="row.status" :active-value="1" :inactive-value="0"
            @change="() => handleStatusChange(row)" :loading="tableLoad" />
        </template>
      </el-table-column>

      <el-table-column prop="operation" label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="openEditDialog(row.id)">
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>
          <el-button size="small" @click="deleteCustomerType(row)" :loading="deleteLoad">
            <el-icon>
              <Delete />
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block" style="float: right;">
      <span style="font-size: 14px;">共 {{ customerTypeList.length }} 条</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const formLabelWidth = '100px'

// 是否处于搜索模式
const searchMode = ref(false)
// 表格加载状态
const tableLoad = ref(false)
// 保存按钮加载状态
const saving = ref(false)
// 删除按钮加载状态
const deleteLoad = ref(false)
// 搜索表单
const searchForm = ref({
  name: '',
  status: '1'
})
// 默认的添加、修改表单结构（用于重置）
const defaultForm = {
  id: null,
  parentId: '0',
  name: '',
}
// 添加、修改表单
const form = ref({ ...defaultForm })

// 对话框状态
const dialogFormVisible = ref(false)
// 对话框类型
const dialogCustomerType = ref('add')
// 客户类别数据
const customerTypeList = ref([])
// 选中的对象
const selections = ref([])


// 构建树形数据
const treeData = computed(() => {

  const roots = []

  const map = {}

  customerTypeList.value.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  customerTypeList.value.forEach(item => {
    if (item.parentId == null || item.parentId == '0') {
      roots.push(map[item.id])
    } else {
      const parentObj = map[item.parentId]
      if (parentObj) {
        parentObj.children.push(map[item.id])
      }
    }
  })
  return roots
})

// 树选择器
const treeSelectData = computed(() => {
  const enabledTreeData = treeData.value
  return [
    {
      id: '0',
      name: '全部',
      children: enabledTreeData
    }
  ]
})

// 选中的id列表
const selectionIds = computed(() => selections.value.map(item => item.id))


// 客户类型分页
const getCustomerTypeList = async () => {
  tableLoad.value = true

  const params = {
    name: searchForm.value.name,
    status: searchForm.value.status == '-1' ? null : searchForm.value.status
  }

  try {
    const res = await axios.get('/api/basic/customer/allCustomerTypes', { params })

    if (res.data.code === 5200) {
      customerTypeList.value = res.data.customerTypeList
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    tableLoad.value = false
  }
}

// 查询
const searchCustomerType = () => {
  if (searchForm.value.name.trim() != '') {
    searchMode.value = true
  } else {
    searchMode.value = false
  }
  getCustomerTypeList()
}

// 刷新
const refresh = () => {
  searchForm.value = { name: '', status: '1' }
  searchMode.value = false
  getCustomerTypeList()
}

// 新增对话
const openAddDialog = () => {
  form.value = { ...defaultForm }
  dialogCustomerType.value = 'add'
  dialogFormVisible.value = true

}

// 编辑对话
const openEditDialog = async (id) => {
  dialogCustomerType.value = 'edit'
  dialogFormVisible.value = true
  try {
    tableLoad.value = true
    const res = await axios.get('/api/basic/customer/customerTypeById', { params: { id } })
    if (res.data.code === 5200) {
      form.value = res.data.customerType
      dialogFormVisible.value = true
    } else {
      ElMessage.error('获取数据失败')
      dialogFormVisible.value = false
    }
  } catch (error) {
    ElMessage.error(error.message)
    dialogFormVisible.value = false
  } finally {
    tableLoad.value = false
  }
}


// 保存数据
const saveCustomerType = async () => {
  saving.value = true
  if (!form.value.name?.trim()) return ElMessage.warning('请输入类别名称')

  try {

    const url = dialogCustomerType.value === 'add' ? '/api/basic/customer/addCustomerType' : '/api/basic/customer/updateCustomerType'

    const res = await axios.post(url, form.value)

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      dialogFormVisible.value = false
      await getCustomerTypeList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    saving.value = false
  }
}

// 删除
const deleteCustomerType = async (row) => {

  if (row.children && row.children.length > 0) {
    ElMessage.error('当前类别下有子类别，请先删除子类别')
    return
  }

  try {
    await ElMessageBox.confirm('此操作将永久删除该类别, 是否继续?', '删除类别', { type: 'warning' })
  } catch {
    return ElMessage.info('取消删除')
  }


  deleteLoad.value = true
  try {
    const res = await axios.post('/api/basic/customer/deleteCustomerType', null, { params: { id: row.id } })
    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      await getCustomerTypeList()
    }
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    deleteLoad.value = false
  }
}

const handleStatusChange = async (row) => {
  tableLoad.value = true
  const originalStatus = row.status
  try {
    const res = await axios.post('/api/basic/customer/updateCustomerTypeStatus', null, {
      params: {
        id: row.id,
        status: originalStatus === 1 ? 0 : 1
      }
    })
    if (res.data.code !== 5200) {
      ElMessage.error('状态更新失败')
    } else {
      ElMessage.success('状态更新成功')
      await getCustomerTypeList()
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
  } finally {
    tableLoad.value = false
  }
}


// 选中多选框
const handleSelectionChange = (selection) => {
  selections.value = selection
}

// 批量禁用
const batchClose = async () => {
  if (selectionIds.value.length === 0) {
    ElMessage.warning('请先选择')
    return
  }
  await batchUpdateStatus(0)
}

// 批量启用
const batchOpen = async () => {
  if (selectionIds.value.length === 0) {
    ElMessage.warning('请先选择')
    return
  }
  await batchUpdateStatus(1)
}

// 批量修改状态
const batchUpdateStatus = async (status) => {

  const params = {
    ids: selectionIds.value,
    status
  }

  try {
    const res = await axios.post("/api/basic/customer/batchUpdateCustomerTypeStatus", params)
    if (res.data.code === 5200) {
      ElMessage.success("修改成功")
      await getCustomerTypeList()
    } else {
      ElMessage.error("修改失败")
    }
  } catch (error) {
    ElMessage.error("修改失败")
  }
}

onMounted(() => {
  getCustomerTypeList()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
  background-color: #fff;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.el-table {
  margin-top: 10px;
}

/* 表格行样式 */
.el-table .el-table__row:nth-child(even) {
  background-color: #f5f7fa;
}

/* 缩进样式 */
.el-table .el-table__row>td:nth-child(2) {
  padding-left: 20px;
}

/* 操作按钮样式 */
.el-button--small {
  padding: 5px 8px;
  font-size: 12px;
}

/* 开关样式 */
.el-switch {
  margin-left: 10px;
}
</style>